from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from .auth import TokenAuthentication
from . import models
import uuid


class LoginView(APIView):
    """用户登录视图"""
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        print(request.user)
        print(request.data)
        user_obj = models.UserInfo.objects.filter(**request.data).first()
        print(user_obj)
        if not user_obj:
            return Response("用户名或者密码错误")
        random_string = str(uuid.uuid4())
        user_obj.token = random_string
        user_obj.save()
        print(request.auth)
        print(request.user)

        return Response(random_string)


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        # fields = '__all__'
        exclude = ['author',]


class ArticleDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ArticleDetail
        exclude = ['article',]


class ArticleListSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = '__all__'


class PageArticleDetailSerializer(serializers.ModelSerializer):
    content = serializers.CharField(source="articledetail.content")
    author = serializers.CharField(source="author.username")
    category = serializers.CharField(source="get_category_display")
    class Meta:
        model = models.Article
        fields = '__all__'


class ArticleView(APIView):
    """文章视图类"""
    authentication_classes = [TokenAuthentication, ]

    def get(self, request, *args, **kwargs):
        """获取文章列表"""
        pk = kwargs.get('pk')
        print(request.auth)
        if not pk:
            condition = {}
            category = request.query_params.get('category')
            if category:
                condition['category'] = category
            # 按照时间倒叙排列
            queryset = models.Article.objects.filter(**condition).order_by('-date')

            pager = PageNumberPagination()
            result = pager.paginate_queryset(queryset, request, self)
            ser = ArticleListSerializer(instance=result, many=True)
            return Response(ser.data)
        article_obj = models.Article.objects.filter(pk=pk).first()
        ser = PageArticleDetailSerializer(instance=article_obj, many=False)

        return Response(ser.data)


    def post(self, request, *args, **kwargs):
        print(request.data)
        ser = ArticleSerializer(data = request.data)
        ser_detail = ArticleDetailSerializer(data = request.data)
        if ser.is_valid() and ser_detail.is_valid():
            # 增加文章
            article_obj = ser.save(author_id=1)
            ser_detail.save(article=article_obj)
            return Response(ser.validated_data)
        print(ser.errors)
        return Response(ser.errors)


    def put(self, request, *args, **kwargs):
        pass


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = '__all__'


# 保存评论的序列化
class PostCommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        exclude = ['user']


class CommentView(APIView):
    """评论接口"""
    authentication_classes = [TokenAuthentication,]

    def get(self, request, *args, **kwargs):
        """评论列表"""
        article_id = request.query_params.get('article')
        queryset = models.Comment.objects.filter(article_id=article_id)
        ser = CommentSerializer(instance=queryset, many=True)
        return Response(ser.data)

    def post(self, request, *args, **kwargs):
        """添加评论"""
        print(request.data)
        ser = PostCommentSerializer(data = request.data)
        if ser.is_valid():
            ser.save(user_id=2)
            return Response("成功")
        return Response('失败')




